package data

import (
	"blog/model"

	"gitee.com/xchengli/blog-lib/database"
	"gitee.com/xchengli/blog-lib/zlog"

	"github.com/gin-gonic/gin"
)

type TagDataService struct{}

// GetTagList 获取标签列表
func (s *TagDataService) GetTagList(ctx *gin.Context, orderBy string, limit uint) []model.TagData {
	var tags []model.TagData
	db := database.GetDB()

	query := db.Model(&model.Tag{})

	switch orderBy {
	case "rand":
		query = query.Order("RAND()")
	case "count":
		query = query.Order("post_count DESC")
	default:
		query = query.Order("id DESC")
	}

	if limit > 0 {
		query = query.Limit(int(limit))
	}

	query.Find(&tags)
	return tags
}

// GetPostTags 获取文章标签
func (s *TagDataService) GetPostTags(ctx *gin.Context, postId int) []model.TagData {
	var tags []model.TagData
	db := database.GetDB()

	err := db.Table("bg_posts_tags").
		Select("id, post_id as content_id, name").
		Where("post_id = ?", postId).
		Find(&tags).Error

	if err != nil {
		zlog.Error(ctx, err)
		return []model.TagData{}
	}

	return tags
}

// GetPostIdsByTagName 通过标签获取文章ID
func (s *TagDataService) GetPostIdsByTagName(ctx *gin.Context, tagName string) []int64 {
	var postIds []int64
	db := database.GetDB()

	err := db.Table("bg_posts_tags").
		Select("DISTINCT post_id").
		Where("name = ?", tagName).
		Pluck("post_id", &postIds).Error

	if err != nil {
		zlog.Error(ctx, err)
		return []int64{}
	}

	return postIds
}
